#!{{ pythonbin }}
# -*- coding: utf-8 -*-
import os, sys
from time import sleep
PORT        = {{ args.port }}
PIDFILE     = "/tmp/{{ pname }}_uwsgi.pid"
LOGFILE     = "/tmp/{{ pname }}_uwsgi.log"
MANAGE      = "{{ pythonbin }} {{ argv0 }}"
BIN         = "uwsgi"


def start(do_test=True):
    if sys.platform != "darwin" and status(False) == 1:
        sys.exit("already running... [QUIT]")
    if do_test:
        test()
    print "start...",
    cmd = "{BIN} -s 0.0.0.0:{PORT} --chdir {{ appdir }} --vacuum --daemonize2 {LOGFILE} --pidfile {PIDFILE} -p {{ num_workers }} --master -w manage --reload-mercy 8 --procname-prefix-spaced {{ pname }} --limit-as 256".format(**globals())
    print cmd
    r = os.system(cmd)
    print "[OK]" if r==0 else "[FAIL]"

def stop():
    if sys.platform != "darwin" and status(False) == 0: sys.exit("not running... [QUIT]")
    print "stop...",
    r = os.system("{BIN} --stop {PIDFILE}".format(**globals()))
    print "[OK]" if r == 0 else "[FAIL]"

def reload():
    if sys.platform != "darwin" and status(False) == 0: sys.exit("not running... [QUIT]")
    test()
    print "reload...",
    r = os.system("{BIN} --reload {PIDFILE}".format(**globals()))
    print "[OK]" if r==0 else "[FAIL]"

def restart():
    if sys.platform != "darwin" and status(False) == 0: sys.exit("not running... [QUIT]")
    test()
    print "restart...",
    r = os.system("kill -TERM `cat {PIDFILE}`".format(**globals()))
    print "[OK]" if r==0 else "[FAIL]"

def status(verbose=True):
    try:
        pid = int(open(PIDFILE).read())
        with open("/proc/%s/status"%pid) as f:
            for line in f.xreadlines():
                if line.startswith("State:"):
                    state = line.split(":")[1].strip()
                    if verbose:
                        print state
                    return 1
    except:
        pass
    if verbose:
        print "not running..."
    return 0

def test():
    print "test...",
    r = os.system("{MANAGE} -h > /dev/null".format(**globals()))
    print "[OK]" if r==0 else "[FAIL]"
    if r != 0: sys.exit(r)

def usage():
    print "%s {start|stop|restart|reload|status|test}"%sys.argv[0]
    sys.exit(0)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        usage()
    if sys.argv[1] in ("start", "stop", "restart", "reload", "test", "status"):
        eval("%s()"%sys.argv[1])
        #globals[sys.argv[1]]()
    else:
        usage()

